package com.ksyzt.ksite2.client.common;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitHandler;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.ksyzt.gwt.client.common.DeleteButton;
import com.ksyzt.gwt.client.common.MessageComposite;
import com.ksyzt.gwt.client.common.SimpleMessage;
import com.ksyzt.gwt.client.event.MessageEvent;
import com.ksyzt.ksite2.shared.modle.ATTACHMENTObj;
import com.ksyzt.ksite2.shared.modle.ATTACHMENTObjs;

public class AttatchmentManager extends MessageComposite {

	private static AttatchmentManagerUiBinder uiBinder = GWT
			.create(AttatchmentManagerUiBinder.class);

	interface AttatchmentManagerUiBinder extends
			UiBinder<Widget, AttatchmentManager> {
	}

	public AttatchmentManager() {
		initWidget(uiBinder.createAndBindUi(this));

		initUploadPanel();
	}

	@UiField
	FormPanel formAction;

	@UiField
	FileUpload uploader;

	@UiField
	Hidden nid;

	private SubmitCompleteHandler m_complete_handler = new SubmitCompleteHandler() {

		@Override
		public void onSubmitComplete(SubmitCompleteEvent event) {
			String jsonstr = event.getResults();

			JSONValue rvalue = JSONParser.parse(jsonstr);
			JSONObject robj = rvalue.isObject();
			JSONString msg = (JSONString) robj.get("err").isString();
			if (msg.stringValue().equals("")) {
				refreshFromServer();

			} else {
				message(msg.stringValue());
			}

		}
	};

	private SubmitHandler m_submit_handler = new SubmitHandler() {

		@Override
		public void onSubmit(SubmitEvent event) {

		}
	};

	private void initUploadPanel() {

		formAction
				.setAction(GWT.getModuleBaseURL() + "../attatchment_uploader");
		formAction.setMethod(FormPanel.METHOD_POST);
		formAction.setEncoding(FormPanel.ENCODING_MULTIPART);
		formAction.addSubmitCompleteHandler(m_complete_handler);
		formAction.addSubmitHandler(m_submit_handler);
		uploader.addChangeHandler(m_file_change);

	}

	private void refreshFromServer() {
		initControl(m_tag, m_id);
	}

	@UiField
	VerticalPanel list;

	private AsyncCallback<Void> m_delete_handler = new AsyncCallback<Void>() {

		@Override
		public void onSuccess(Void result) {
			refreshFromServer();
		}

		@Override
		public void onFailure(Throwable caught) {
			Window.alert(caught.getMessage());
		}
	};

	private ClickHandler m_delete_click = new ClickHandler() {

		@Override
		public void onClick(ClickEvent event) {
			DeleteButton btn = (DeleteButton) event.getSource();
			int aid = btn.getValue();
			ServerProxy.SYS_MANAGER.deleteAttatchment(aid, m_delete_handler);

		}
	};
	private AsyncCallback<ATTACHMENTObjs> m_attatchment_handler = new AsyncCallback<ATTACHMENTObjs>() {

		@Override
		public void onSuccess(ATTACHMENTObjs result) {
			list.clear();
			for (ATTACHMENTObj a : result) {
				HorizontalPanel hp = new HorizontalPanel();
				hp.setSpacing(2);
				DeleteButton del = new DeleteButton(a.getAID());
				del.addClickHandler(m_delete_click);
				hp.add(del);
				Anchor link = new Anchor(a.getTITLE());
				link.setHref("../attatchment?tag=" + a.getTAG());
				link.setTarget("_blank");
				hp.add(link);

				Label l = new Label("下载次数" + a.getDCOUNT());
				hp.add(l);
				list.add(hp);
			}

			if (result.size() == 0) {
				list.add(new SimpleMessage("没有附件"));
			}

		}

		@Override
		public void onFailure(Throwable caught) {
			list.clear();
			list.add(new Label(caught.getMessage()));
		}
	};
	String m_tag;
	Integer m_id;

	public boolean canUpload(String ft) {
		boolean b = false;

		if (ft.compareToIgnoreCase("zip") == 0
				|| ft.compareToIgnoreCase("png") == 0
				|| ft.compareToIgnoreCase("bmp") == 0
				|| ft.compareToIgnoreCase("jpg") == 0
				|| ft.compareToIgnoreCase("jpeg") == 0
				|| ft.compareToIgnoreCase("swf") == 0
				|| ft.compareToIgnoreCase("doc") == 0
				|| ft.compareToIgnoreCase("xls") == 0
				|| ft.compareToIgnoreCase("xlsx") == 0
				|| ft.compareToIgnoreCase("docx") == 0
				|| ft.compareToIgnoreCase("gif") == 0
				|| ft.compareToIgnoreCase("txt") == 0
				|| ft.compareToIgnoreCase("pdf") == 0
				|| ft.compareToIgnoreCase("zip") == 0
				|| ft.compareToIgnoreCase("rar") == 0
				|| ft.compareToIgnoreCase("tar") == 0
				|| ft.compareToIgnoreCase("gz") == 0)
			b = true;
		return b;
	}

	private ChangeHandler m_file_change = new ChangeHandler() {

		public void onChange(ChangeEvent event) {
			String fn = uploader.getFilename();
			if (uploader.getFilename().equals("")) {
				message("选择文件?");
			} else {
				int lastdot = fn.lastIndexOf('.');
				if (lastdot > 0) {
					String title = "";
					int start = fn.lastIndexOf("\\");
					if (start < 0) {
						start = 0;
					} else {
						start++;
					}

					title = fn.substring(start, lastdot);
					txtTitle.setValue(title);
					String filetype = fn.substring(lastdot + 1);
					if (canUpload(filetype)) {
						btnSubmit.setEnabled(true);
						message("");

					} else {
						message("不能上传此文件格式");
					}
				}
			}
		}
	};

	@UiField
	TextBox txtTitle;
	@UiField
	Button btnSubmit;

	@UiField
	Label lbMessage;

	@UiHandler("btnSubmit")
	void onSubmit(ClickEvent e) {
		formAction.submit();
	}

	@UiField
	Button btnCancel;

	@UiHandler("btnCancel")
	void onCancel(ClickEvent e) {
		MessageEvent ev = new MessageEvent(MessageEvent.CANCEL, 0);
		fireEvent(ev);
	}

	public void message(String msg) {
		lbMessage.setText(msg);
	}

	public void initControl(String tag, Integer newsid) {
		formAction.reset();
		btnSubmit.setEnabled(false);
		message("");
		m_tag = tag;
		m_id = newsid;
		nid.setValue(tag + newsid);
		list.clear();
		if (m_id == null) {
			uploader.setEnabled(false);
		} else {
			uploader.setEnabled(true);
			ServerProxy.SYS_MANAGER.getAttatchments(nid.getValue(),
					m_attatchment_handler);
		}
	}

}
